//
//  SearchArtifactViewController.m
//  GiftSay
//
//  Created by QQn1993 on 16/1/9.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "SearchArtifactViewController.h"
#import "HotWordsCollectionReusableView.h"
#import "HotWordsCollectionViewCell.h"
#import "Filters.h"
#import "Channel.h"

@interface SearchArtifactViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,HotWordsCollectionReusableViewDelgate>

@property (nonatomic,strong) UICollectionView *collection;
@property (nonatomic,strong) UICollectionView *choseCollection;

@property (nonatomic,assign) NSInteger number;

@property (nonatomic,strong) Animal *animal;

//数组们
@property (nonatomic,strong) NSMutableArray *itemsArray;
@property (nonatomic,strong) NSMutableArray *hotChanal;
@property (nonatomic,strong) Filters *filter;

@property (nonatomic,assign) CGFloat contenty;

@property (nonatomic,copy) NSString *datasourceUrl;

@end

static int scrolltimes = 0;

@implementation SearchArtifactViewController

- (void)viewWillAppear:(BOOL)animated
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.navigationController.navigationBar.barTintColor = kNightModeNavigationColor;
        self.collection.backgroundColor = kNightModeColor;
        self.choseCollection.backgroundColor = kNightModeColor;
    } else {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.number = 0;
    self.itemsArray = [NSMutableArray arrayWithCapacity:0];
    
    self.datasourceUrl = [NSString stringWithFormat:@"%@%ld",kSearchArtifyUrl,self.number * 20];
    self.hotChanal = [NSMutableArray arrayWithCapacity:0];
    [self getaDatource];
    
    HotWordsCollectionReusableView *hot = [[HotWordsCollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kWidth / 10)];
    hot.array = [NSArray arrayWithArray:self.array];
    self.filter = self.array[0];
    hot.delegate = self;
    
    [self.view addSubview:hot];
    hot.tag = 111111;

//    [self getDatasourceForHeard];
    [self createdCollectionview];
    [self createdWordsCollectionview];
    
    self.animal = [[Animal alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.animal];
    //添加动画结束的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animalStop:) name:@"tag" object:nil];
    
}

#pragma mark 动画结束监听方法
- (void)animalStop:(NSNotification *)object
{
    [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
    
    self.animal.frame = CGRectMake(0, 0, 0, 0);
    self.animal.contetsize = CGSizeZero;
}

#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        NSLog(@"下拉刷新");
        
        self.animal.frame = CGRectMake(0, kWidth / 10 + kHeight / 150 , self.view.width, 60);
        self.animal.contetsize = CGSizeMake(kWidth, 60);
        
        [self.animal strat];
        
        [self reload];
    }
    
}



#pragma mark 刷新
- (void)reload
{
    NSLog(@"刷新");
    if (self.itemsArray.count > 0) {
        [self.itemsArray removeAllObjects];
    }
    
    HotWordsCollectionReusableView *hot = (HotWordsCollectionReusableView *)[self.view viewWithTag:111111];
    
    hot.select = !hot.select;
#pragma mark 取出指定标签更改标题
    for (Filters *filtee in hot.array) {
        if ([filtee isEqual:self.filter]) {
            NSIndexPath *indext = [NSIndexPath indexPathForRow:[hot.array indexOfObject:filtee] inSection:0];
            HotWordsCollectionViewCell *cell = (HotWordsCollectionViewCell *)[hot.collection cellForItemAtIndexPath:indext];
            cell.select = !cell.select;
            cell.name = [NSString stringWithFormat:@"%@ ▽",[self.filter name]];
        }
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        self.choseCollection.frame = CGRectMake(0, kWidth / 10, kWidth, CGFLOAT_MIN);
    }];

    if (self.number != 0) {
        self.number = 0;
    }
    
    [self getaDatource];
}

#pragma mark 加载
- (void)addItem
{
    NSLog(@"加载");
    
    self.number += 1;
    [self getaDatource];
}

//创建collectionview

- (void)createdCollectionview
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 50, kWidth / 50, kWidth/50, kWidth/50);
    
    flow.minimumInteritemSpacing = kWidth / 50;
    flow.minimumLineSpacing = kWidth / 50;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kWidth / 10, self.view.size.width, self.view.size.height - 64 - kWidth / 10) collectionViewLayout:flow];
    self.collection.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    [self.collection registerClass:[BaseCollectionViewCell class] forCellWithReuseIdentifier:@"BaseCollectionViewCell"];
    

    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.view addSubview:self.collection];
}
#pragma mark 创建下拉collectionview

- (void)createdWordsCollectionview
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 50, kWidth / 50, kWidth/50, kWidth/50);
    
    flow.minimumInteritemSpacing = kWidth / 50;
    flow.minimumLineSpacing = kWidth / 50;
    
    self.choseCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kWidth / 10, kWidth, CGFLOAT_MIN) collectionViewLayout:flow];
    [self.choseCollection registerClass:[HotWordsCollectionViewCell class] forCellWithReuseIdentifier:@"HotWordsCollectionViewCell"];
    
    [self.choseCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    self.choseCollection.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.8];
    
    self.choseCollection.delegate = self;
    self.choseCollection.dataSource = self;
    
    [self.view addSubview:self.choseCollection];

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.collection]) {
        return CGSizeMake(kWidth / 50 * 23, kHeight / 10 * 4);
    }
    else if ([collectionView isEqual:self.choseCollection] && indexPath.row > 0 && (self.filter.channel.count ) > indexPath.row){
        
        CGRect rect = [QQNGetRect string:[self.filter.channel[indexPath.row - 1] name] font:25*SCREEN_WIDTH];
        return rect.size;
    }
    else if ([collectionView isEqual:self.choseCollection] && indexPath.row == 0 && (self.filter.channel.count ) > indexPath.row){
        
        CGRect rect = [QQNGetRect string:@"全部" font:25*SCREEN_WIDTH];
        return rect.size;
    }

    else{
        return CGSizeZero;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeZero;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([collectionView isEqual:self.collection]) {
       return  self.itemsArray.count;
    }
    
    else if ([collectionView isEqual:self.choseCollection] && self.filter.channel.count > 0){
        return self.filter.channel.count + 1;
    }
    
    else{
        return 1;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *celll = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    if ([collectionView isEqual:self.collection]) {
        BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BaseCollectionViewCell" forIndexPath:indexPath];
        if (self.itemsArray.count > indexPath.row) {
            cell.item = self.itemsArray[indexPath.row];
        }
        return cell;
    }
    else if ([collectionView isEqual:self.choseCollection] &&  (self.filter.channel.count + 1) > indexPath.row){
        HotWordsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotWordsCollectionViewCell" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.name = @"全部";
        }
        
        else{
            cell.name = [self.filter.channel[indexPath.row - 1] name];
        }
        return cell;
    }
    
    return celll;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contenty) {
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
            
            //加载更多数据
            if (scrolltimes == 0) {
                [self addItem];
                scrolltimes = 1;
            }
        }
    }
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.collection]) {
        Items *item = self.itemsArray[indexPath.row];
        
        WebViewController *web = [[WebViewController alloc] init];
        web.url = [NSString stringWithFormat:@"%@%@",kItemsInfo,item.ID];
        //可拼接web
        //    web.url = [NSString stringWithFormat:@"%@%@",kItemsInfoTow,item.ID];
        //    web.type = @"itemshtml";
        [self.navigationController pushViewController:web animated:YES];
    }
    
#pragma mark 切换数据时选全部的时候
    else if ([collectionView isEqual:self.choseCollection] && indexPath.row == 0){
        
#pragma mark 判断字符串是否包含某个标签
        NSRange range = [self.datasourceUrl rangeOfString:self.filter.key];
        //包含
        if (range.length > 0) {
            NSArray *array = [self.datasourceUrl componentsSeparatedByString:@"&"];
            for (NSString *str in array) {
                NSRange temp = [str rangeOfString:self.filter.key];
                if (temp.length > 0) {
                    self.datasourceUrl = [self.datasourceUrl stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"&%@",str] withString:@""];
                    [self reload];
                }
            }
        }
        
        
    }
    
#pragma mark 切换数据选其他标签时
    else if ([collectionView isEqual:self.choseCollection] && indexPath.row > 0){
        
        NSString *temp = [NSString stringWithFormat:@"%@=%@",self.filter.key,[self.filter.channel[indexPath.row - 1] key]];
//        NSLog(@"%@",self.filter.name);
        NSRange range = [self.datasourceUrl rangeOfString:self.filter.key];
#pragma mark 如果包含当前标签
        if (range.length >0)//包含
        {
            NSRange ra = [self.datasourceUrl rangeOfString:temp];
            //取出全部标签，判断当前选择是否没变 ra.length == 0 为没变
            if (ra.length == 0) {
                NSArray *array = [self.datasourceUrl componentsSeparatedByString:@"&"];
                //遍历，替换或者拼接，刷新
                for (NSString *str in array) {
                    NSRange ceshi = [str rangeOfString:self.filter.key];
                    if (ceshi.length > 0) {
                        self.datasourceUrl = [self.datasourceUrl stringByReplacingOccurrencesOfString:str withString:temp];
                        [self reload];
                        return;
                    }
                    else if (ceshi.length == 0 && [str isEqual:[array lastObject]]){
                        self.datasourceUrl = [self.datasourceUrl stringByAppendingString:[NSString stringWithFormat:@"&%@",temp]];
                        [self reload];
                        return;
                    }
                }
            }
        }
        //不包含，直接刷新
        else{
            self.datasourceUrl = [self.datasourceUrl stringByAppendingString:[NSString stringWithFormat:@"&%@",temp]];
            [self reload];
        }
        
    }
    
}

//获取数据
- (void)getaDatource
{
    [LYKNetWorkTool getWithUrl:self.datasourceUrl parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
        
        NSDictionary *dicforData = [NSDictionary dictionaryWithDictionary:any[@"data"]];
        
        NSArray *items = [NSArray arrayWithArray:dicforData[@"items"]];
        
        if (items.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有商品了" message:@"换个别的吧" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        
//        NSLog(@"%@",items);
        
        for (NSDictionary *datasource in items) {
            
//            NSDictionary *dic = datasource[@"data"];
            Items *item = [[Items alloc] init];
            item.like = [NSString stringWithFormat:@"%@",datasource[@"favorites_count"]];
            item.ID = [NSString stringWithFormat:@"%@",datasource[@"id"]];
            item.cover_icon = datasource[@"cover_image_url"];
            item.title = datasource[@"name"];
            item.price = [NSString stringWithFormat:@"%@",datasource[@"price"]];
            
            [self.itemsArray addObject:item];
        }
        
        NSLog(@"%ld",self.itemsArray.count);
        
        [self.collection reloadData];
        
        scrolltimes = 0;
        
    } fail:^(NSError *erro) {
        
    }];
}

#pragma mark 代理
- (void)sendMessage:(NSDictionary *)dic
{
//    NSLog(@"%@",dic);
    if ([dic valueForKey:@"select"] == [NSNumber numberWithInt:1]) {
        self.filter = dic[@"model"];
        NSLog(@"%@",self.filter.name);
        [UIView animateWithDuration:0.5 animations:^{
            self.choseCollection.frame = CGRectMake(0, kWidth / 10, kWidth, self.collection.frame.size.height);
            [self.choseCollection reloadData];
        }];
    }
    
    else if ([dic valueForKey:@"select"] == [NSNumber numberWithInt:0]){
        
        [UIView animateWithDuration:0.5 animations:^{
            self.choseCollection.frame = CGRectMake(0, kWidth / 10, kWidth, CGFLOAT_MIN);
        }];
        
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
